/*jslint sloppy: true */
/*global probe, angular */
probe.controller('CaseEditorCode', function ($scope, ocDialog, GET_FRAME, $timeout,
											 Capture, scriptEngine) {
	var $cm, DI = $scope.$parent.DI, pScope = $scope.$parent, //TODO controller as
		previousLine = 0;//code mirror instance;
	
	function useCodingMode() {
		pScope.isCaseSimple = false;
		$scope.editorOptions.readOnly = false;
		pScope['case'].code = pScope['case'].code.replace('//simple case\n', '');
	}
	
	$scope.caseCodeMirrorRefresh = true;
	$scope.undo = function () {
		$cm.undo();
	};
	$scope.redo = function () {
		$cm.redo();
	};

	$scope.parseConsole = '';
	
	$scope.capture = function () {
		GET_FRAME().style.backgroundColor = '#ffffff';
		Capture.setZIndex(550).setContext(GET_FRAME().contentWindow);
		
		Capture.watchHTML(function (selector) {
			GET_FRAME().style.zIndex = 0;
			GET_FRAME().style.backgroundColor = '';
			
			//insert at current selection
			$cm.replaceSelection('"' + selector + '"');
		});
	};
	$scope.insertField = function () {
		throw new Error("todo");
	};

    $scope.editorOptions = {
        lineWrapping : true,
        lineNumbers: true,
	    matchBrackets: true,
	    mode: "text/x-php",
	    indentWithTabs: true,
	    indentUnit: 4,
	    //can't edit in simple case
	    readOnly: true,
		//automatically refresh
	    autoRefresh: true,
		onLoad: function (cm) {
			$cm = cm;
		}
    };

	$scope.enableCoding = function () {
		ocDialog.alert({
			title: '确认转换',
			message: '启用编辑源码，您当前的用例\n' +
				'将无法使用简单视图编辑。\n' +
				'（建议您先保存一次简单用例，再启用编辑源码）',
			callFn: useCodingMode
		}, DI);
	};

	$scope.parse = function () {
		//reset case before parse
		$scope['case'].cp = null;
		scriptEngine.setup({
			contextFrame: GET_FRAME()
		});

		scriptEngine.parse($scope['case'].code)(function (err, ast) {
			if (err) {
				$scope.parseConsole = err.toString();
			} else {
				$scope.parseConsole = '分析成功：' + angular.toJson(ast, true);
			}
		});
	};
	$scope.code = '';
	pScope.refreshCodeModeCode = function (newCode) {
		$scope.code = newCode;
	};

	// init
	$scope.$watchGroup(['$parent.case.code', '$parent.editorMode'], function () {
		$scope.caseCodeMirrorRefresh = !$scope.caseCodeMirrorRefresh;
	});

	pScope.codeEmphasize = function (currentIns) {
		var line = currentIns.LINE;
		if (!line) {
			return;//main process does not have a line currently...
		}
		//line offset
		line -= 1;
		$cm.removeLineClass(previousLine, 'background');
		$cm.addLineClass(line, 'background', 'current-line');
		previousLine = line;
	};
});
